package com.example.identifyvisio.controller;


import cn.hutool.core.date.StopWatch;
import com.example.identifyvisio.model.R;
import com.example.identifyvisio.model.ReqData;
import com.example.identifyvisio.model.RespData;
import com.example.identifyvisio.model.VisioJson;
import com.example.identifyvisio.service.VisioService;
import com.example.identifyvisio.utis.Json;
import com.example.identifyvisio.utis.UnzipFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


import static com.example.identifyvisio.service.LogicalProcessing.parsePageXml;
import static com.example.identifyvisio.utis.HttpRestTemplate.post;
import static com.example.identifyvisio.utis.ProcessFileUtil.deleteDirectoryContents;
import static com.example.identifyvisio.utis.VisioFileUtil.getTypeMap;


@RestController
@CrossOrigin
@Slf4j
public class VSDXController {
    @Autowired
    VisioService visioService;
    //临时文件保存地址
/*    @Value("${file.outputFolder}")
    private String outputFolder;
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;
    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucketName;
    @Value("${spring.cloud.alicloud.access-key}")
    private String accessKeyId;
    @Value("${spring.cloud.alicloud.secret-key}")
    private String accessKeySecret;*/
    String outputFolder = "C:\\Users\\ms206\\Desktop\\visio图\\代码解压\\";

    public static void main(String[] args) {
        String folder = "C:\\Users\\ms206\\Desktop\\visio图\\跨行来账-修改.vsdx";
        ReqData reqData = new ReqData();
        reqData.setFileName(folder);
        VSDXController vsdxController = new VSDXController();
        vsdxController.uploadFile(reqData);
    }

    @PostMapping("/upload")
    public RespData uploadFile(@RequestBody ReqData data) {
        StopWatch stopWatch = new StopWatch("多阶段任务计时");

        stopWatch.start("第一阶段：解压文件");
        //阿里参数
        HashMap<String, String> ossMap = new HashMap<>(4);
/*        ossMap.put("endpoint",endpoint);
        ossMap.put("bucketName",bucketName);
        ossMap.put("accessKeyId",accessKeyId);
        ossMap.put("accessKeySecret",accessKeySecret);*/
        // 定义目录路径
        Path dir = Paths.get(outputFolder);
        try {
            // 判断解压目录是否存在，如果不存在则创建
            if (!Files.exists(dir)) {
                Files.createDirectories(dir);
            } else {
                // 删除目录下的所有文件和子目录
                deleteDirectoryContents(dir);
            }
            UnzipFileUtil fileUtil = new UnzipFileUtil();
            //解压visio
            fileUtil.unzip(data.getFileName(), outputFolder, ossMap);
            stopWatch.stop();

            stopWatch.start("第二阶段：处理节点");
            // 解析masters文件获取各中类型的Master值
            String masterFilePath = outputFolder + "visio\\masters\\masters.xml";
            HashMap<String, String> typeMap = getTypeMap(masterFilePath);

            ArrayList<String> jsonList = new ArrayList<>();
            int i = 1;
            while (true) {
                String pageFilePath = outputFolder + "visio\\Pages\\Page" + i + ".xml";
                Path patExist = Paths.get(pageFilePath);
                if (!Files.exists(patExist)) {
                    break;
                }
                ArrayList<String> pageList = parsePageXml(pageFilePath, typeMap);
                String json = pageList.get(0);
                jsonList.add(json);
                i++;
            }


            // 解析并转换为JSON
            System.out.println(jsonList.get(0));
            String escapedJson = jsonList.get(0).replace("\"", "\\\"");
            String str = "{\n" + "  \\\"cells\\\": " + escapedJson + "  \n" + "}";
            stopWatch.stop();
            // 打印总运行时间和每个阶段的运行时间
            log.info(stopWatch.prettyPrint(TimeUnit.MILLISECONDS));
            Json json1 = new Json();

            post(json1.addJson(str));
            // 如果一切正常，返回成功响应
            return new RespData("上传成功", str, 200);
        } catch (Exception e) {
            log.error("报错信息：", e);
            // 如果发生错误，记录日志并返回错误响应
            return new RespData(e.getMessage(), null, 500);
        }
    }

    @PostMapping("/getPage")
    public R<Integer> getPage(@RequestBody ReqData data) {
        //阿里参数
        HashMap<String, String> ossMap = new HashMap<>(4);
/*        ossMap.put("endpoint",endpoint);
        ossMap.put("bucketName",bucketName);
        ossMap.put("accessKeyId",accessKeyId);
        ossMap.put("accessKeySecret",accessKeySecret);*/
        // 定义目录路径
        Path dir = Paths.get(outputFolder);
        int i = 1;
        try {
            // 判断解压目录是否存在，如果不存在则创建
            if (!Files.exists(dir)) {
                Files.createDirectories(dir);
            } else {
                // 删除目录下的所有文件和子目录
                deleteDirectoryContents(dir);
            }
            UnzipFileUtil fileUtil = new UnzipFileUtil();
            //解压visio
            fileUtil.unzip(data.getFileName(), outputFolder, ossMap);
            while (true) {
                String pageFilePath = outputFolder + "visio\\Pages\\Page" + i + ".xml";
                Path patExist = Paths.get(pageFilePath);
                if (!Files.exists(patExist)) {
                    break;
                }
                i++;
            }
        }catch (Exception e){
            log.error("报错信息：", e);
            R<Integer> exceR = new R<>();
            exceR.setMsg(e.getMessage());
            // 如果发生错误，记录日志并返回错误响应
            return exceR;
        }
        R<Integer> successR = new R<>();
        successR.setData(i -1);
        successR.setMsg("获取页面");
        return successR;
    }

    @PostMapping("/store")
    public R getData(@RequestBody ReqData data){
       try {
           // 解析masters文件获取各中类型的Master值
           String masterFilePath = outputFolder + "visio\\masters\\masters.xml";
           HashMap<String, String> typeMap = getTypeMap(masterFilePath);
           ArrayList<Integer> pageList = data.getPageList();

           int size = pageList.size();
           ArrayList<VisioJson> jsonList = new ArrayList<>(size);
           VisioJson visioJson = new VisioJson();
           visioJson.setVisioNm(data.getFileName());
           visioJson.setSheetNm(data.getPageList().size());

           for (int i = 0; i < size; i++) {
               String pageFilePath = outputFolder + "visio\\Pages\\Page" + pageList.get(i) + ".xml";
               ArrayList<String> pageDataList = parsePageXml(pageFilePath, typeMap);

               visioJson.setJsonContext(pageDataList.get(0));
               visioJson.setMsg(pageDataList.get(1));
               jsonList.add(visioJson);
           }
           //存库
           visioService.insertList(jsonList);
       }catch (Exception e){
           log.error("报错信息：", e);
           R<Integer> exceR = new R<>();
           exceR.setMsg(e.getMessage());
           // 如果发生错误，记录日志并返回错误响应
           return exceR;
       }
        R<Integer> successR = new R<>();
        successR.setMsg("存库成功");
        return successR;
    }
}
